<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JAVA时间处理 | 后端学习记录</title><meta name="keywords" content="Java"><meta name="author" content="h0ss"><meta name="copyright" content="h0ss"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、时间线&#x2F;时间戳时间戳通常是一个字符序列，唯一地标志某一刻的时间。Java 中时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数。在程序中可以通过三种方式去获取时间戳： 1、Date类util.Date类是JDK1.0引入的时间相关类，但随着JDK的发展，许多方法都已经被Deprecated，目前只有两个构造器是处于非过时状态，并且由于JDK1.8引入time下的几">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA时间处理">
<meta property="og:url" content="https://blog.gpnusz.cn/2021/02/08/JAVA%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="后端学习记录">
<meta property="og:description" content="一、时间线&#x2F;时间戳时间戳通常是一个字符序列，唯一地标志某一刻的时间。Java 中时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数。在程序中可以通过三种方式去获取时间戳： 1、Date类util.Date类是JDK1.0引入的时间相关类，但随着JDK的发展，许多方法都已经被Deprecated，目前只有两个构造器是处于非过时状态，并且由于JDK1.8引入time下的几">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://images.cdn.uniqueway.com/uploads/2015/07/396d70b3-6f09-4a4d-8705-7804be013999.jpg">
<meta property="article:published_time" content="2021-02-08T08:26:06.000Z">
<meta property="article:modified_time" content="2022-08-20T18:17:56.909Z">
<meta property="article:author" content="h0ss">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://images.cdn.uniqueway.com/uploads/2015/07/396d70b3-6f09-4a4d-8705-7804be013999.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://blog.gpnusz.cn/2021/02/08/JAVA%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-08-21 02:17:56'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">后端学习记录</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JAVA时间处理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-08T08:26:06.000Z" title="发表于 2021-02-08 16:26:06">2021-02-08</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-08-20T18:17:56.909Z" title="更新于 2022-08-21 02:17:56">2022-08-21</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span></div></div></div><article class="post-content" id="article-container"><h3 id="一、时间线-时间戳"><a href="#一、时间线-时间戳" class="headerlink" title="一、时间线/时间戳"></a>一、时间线/时间戳</h3><p>时间戳通常是一个字符序列，唯一地标志某一刻的时间。Java 中时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数。在程序中可以通过三种方式去获取时间戳：</p>
<h4 id="1、Date类"><a href="#1、Date类" class="headerlink" title="1、Date类"></a>1、Date类</h4><p>util.Date类是JDK1.0引入的时间相关类，但随着JDK的发展，许多方法都已经被Deprecated，目前只有两个构造器是处于非过时状态，并且由于JDK1.8引入time下的几个时间类，因而Date类的使用频率会比较低。</p>
<h5 id="1）构造器一：new-Date"><a href="#1）构造器一：new-Date" class="headerlink" title="1）构造器一：new Date()"></a>1）构造器一：new Date()</h5><p>使用该构造器可以创建当前时间的Date对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Date date1 = <span class="keyword">new</span> Date();</span><br><span class="line">date1.toString(); <span class="comment">//Wed Feb 03 19:57:19 CST 2021</span></span><br></pre></td></tr></table></figure>

<h5 id="2）获取时间戳"><a href="#2）获取时间戳" class="headerlink" title="2）获取时间戳"></a>2）获取时间戳</h5><p>通过调用util.Date下的getTime方法可以获取时间戳返回值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> dateTime = date1.getTime(); <span class="comment">//1612353439901L</span></span><br></pre></td></tr></table></figure>

<h5 id="3-构造器二：new-Date-long-millis"><a href="#3-构造器二：new-Date-long-millis" class="headerlink" title="3) 构造器二：new Date(long millis)"></a>3) 构造器二：new Date(long millis)</h5><p>该构造器会根据传入的long值(ms值) 创建一个Date对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Date date2 = <span class="keyword">new</span> Date(<span class="number">1612353439901L</span>);</span><br><span class="line"><span class="comment">//Wed Feb 03 19:57:19 CST 2021</span></span><br></pre></td></tr></table></figure>

<h4 id="2、Instant类"><a href="#2、Instant类" class="headerlink" title="2、Instant类"></a>2、Instant类</h4><p>Instant表示时间线上的某个点，Instant可往回追溯10亿年(Instant.MIN)，往后可至公元10亿年(Instant.MAX)。通过调用Instant.now()可以获取中时区的时间。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Instant instant = Instant.now();</span><br><span class="line">System.out.println(instant);<span class="comment">//2021-02-08T06:53:36.920611400Z</span></span><br></pre></td></tr></table></figure>

<p>要得到东八区的时间 需要设置偏移量 afOffset()方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">OffsetDateTime time = instant.atOffset(ZoneOffset.ofHours(<span class="number">8</span>));</span><br><span class="line">System.out.println(time);<span class="comment">//2021-02-08T14:53:36.920611400+08:00</span></span><br></pre></td></tr></table></figure>

<p>调用toEpochMilli() 获取自1970.1.1 0:0:0（TUC）到现在的毫秒数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> milli = instant.toEpochMilli();</span><br><span class="line">System.out.println(milli);<span class="comment">//1612767216920</span></span><br></pre></td></tr></table></figure>

<p>调用ofEpochMilli 通过给定的毫秒数 得到Instant对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Instant instant1 = Instant.ofEpochMilli(<span class="number">1612441348036L</span>);</span><br><span class="line">System.out.println(instant1);<span class="comment">//2021-02-04T12:22:28.036Z</span></span><br></pre></td></tr></table></figure>

<p>此外，还可以将Instant对象作为时间戳，利用Duration类进行时间差的计算</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Instant start = Instant.now();</span><br><span class="line">runProcess();</span><br><span class="line">Instant end = Instant.now();</span><br><span class="line">Duration duration = Duration.between(start, end);</span><br><span class="line"><span class="keyword">long</span> millis = duration.toMillis(); <span class="comment">//112ms</span></span><br><span class="line"><span class="keyword">long</span> nanos = duration.toNanos(); <span class="comment">//112645500ns</span></span><br></pre></td></tr></table></figure>

<h4 id="3、System类"><a href="#3、System类" class="headerlink" title="3、System类"></a>3、System类</h4><p>通过调用System类中的currentTimeMillis方法可以得到一个long型的数值，用于表示时间戳，单位为ms</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> millis = System.currentTimeMillis();</span><br></pre></td></tr></table></figure>



<h3 id="二、本地时间-日期"><a href="#二、本地时间-日期" class="headerlink" title="二、本地时间/日期"></a>二、本地时间/日期</h3><h4 id="1、Calendar类"><a href="#1、Calendar类" class="headerlink" title="1、Calendar类"></a>1、Calendar类</h4><p>Calendar是JDK1.1引入的一个关于时间操作的类，引入之后即替代JDK1.0Date类的许多方法，直到JDK8.0TimeAPI的引入。Calendar是一个抽象类，有一个静态方法getInstance返回的其实是子类对象GregorianCalendar。</p>
<p>它的实例化有两种方式，方式一是创建子类GregorianCalendar的对象，方式二是调用Calendar的静态方法getInstance返回子类对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//方式一：</span></span><br><span class="line">GregorianCalendar gregorianCalendar = <span class="keyword">new</span> GregorianCalendar();</span><br><span class="line"><span class="comment">//方式二：</span></span><br><span class="line">Calendar calendar = Calendar.getInstance();</span><br></pre></td></tr></table></figure>

<p>Calendar的常用方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//get()方法</span></span><br><span class="line"><span class="comment">//返回calendar对象的日期是这个月的第几天</span></span><br><span class="line">calendar.get(Calendar.DAY_OF_MONTH);</span><br><span class="line"><span class="comment">//返回calendar对象的日期是今年的第几天</span></span><br><span class="line">calendar.get(Calendar.DAY_OF_YEAR);</span><br><span class="line"><span class="comment">//需要注意的是 Calendar中星期日是1 星期六是7</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//set()方法</span></span><br><span class="line"><span class="comment">//将当前calendar对象的日期修改为当前月的第二十二天 </span></span><br><span class="line"><span class="comment">//也就是从 2021/02/04---&gt;2021/02/22</span></span><br><span class="line">calendar.set(Calendar.DAY_OF_MONTH,<span class="number">22</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//add()方法</span></span><br><span class="line"><span class="comment">//将当前calendar对象的日期往后加3天 </span></span><br><span class="line"><span class="comment">//也就是从 2021/02/22---&gt;2021/02/25</span></span><br><span class="line">calendar.add(Calendar.DAY_OF_MONTH,<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//getTime()：日历---&gt;Date</span></span><br><span class="line">Date date1 = calendar.getTime();</span><br><span class="line"><span class="comment">//setTime()：Date---&gt;日历</span></span><br><span class="line">Date date2 = <span class="keyword">new</span> Date();</span><br><span class="line">calendar.setTime(date2);</span><br></pre></td></tr></table></figure>

<h4 id="2、Java-time-API"><a href="#2、Java-time-API" class="headerlink" title="2、Java.time API"></a>2、Java.time API</h4><h5 id="1）创建对象"><a href="#1）创建对象" class="headerlink" title="1）创建对象"></a>1）创建对象</h5><p>time中代表日期的类是LocalDate，代表时间的LocalTime，日期时间兼备的是LocalDateTime，构建相应的对象可以调用他们的静态方法：now或of。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// now()</span></span><br><span class="line">LocalDate localDate = LocalDate.now();<span class="comment">//2021-02-08</span></span><br><span class="line">LocalTime localTime = LocalTime.now();<span class="comment">//15:27:26.852337600</span></span><br><span class="line"><span class="comment">//2021-02-08T15:27:26.852337600</span></span><br><span class="line">LocalDateTime localDateTime = LocalDateTime.now();</span><br><span class="line"></span><br><span class="line"><span class="comment">//of() 设置指定的时间是不存在偏移量的 准确反映</span></span><br><span class="line"><span class="comment">//2020-12-31T23:50</span></span><br><span class="line">LocalDateTime time = LocalDateTime.of(<span class="number">2020</span>, <span class="number">12</span>, <span class="number">31</span>, <span class="number">23</span>, <span class="number">50</span>);</span><br></pre></td></tr></table></figure>

<h5 id="2）变更属性"><a href="#2）变更属性" class="headerlink" title="2）变更属性"></a>2）变更属性</h5><p>与Calendar类不同，LocalDate等实例是不可变的，一旦对于属性有修改会返回一个新的实例对象，这也进一步弥补了Calendar的不足。</p>
<p>设置相关属性：withXxx()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//将localDateTime对象的日期修改当月第一天</span></span><br><span class="line">LocalDateTime ldt = localDateTime.withDayOfMonth(<span class="number">1</span>);</span><br><span class="line"><span class="comment">//output：2021-02-01T15:27:26.852337600</span></span><br></pre></td></tr></table></figure>

<p>修改相关属性： plusXxx() minusXxx()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// plusXxx(n)： 在现有属性值加上n</span></span><br><span class="line"><span class="comment">//将localDateTime对象的月份向后+3</span></span><br><span class="line">LocalDateTime ldt2 = localDateTime.plusMonths(<span class="number">3</span>);</span><br><span class="line"><span class="comment">//output：2021-05-08T15:27:26.852337600</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// minusXxx(n)： 在现有属性值减去n</span></span><br><span class="line"><span class="comment">//将localDateTime对象的天数-3</span></span><br><span class="line">LocalDateTime ldt3 = localDateTime.minusDays(<span class="number">3</span>);</span><br><span class="line"><span class="comment">//output：2021-02-05T15:27:26.852337600</span></span><br></pre></td></tr></table></figure>

<p>这里需要注意的是，如果创建出不存在的日期（02-31…），那么这些方法会返回该月的有效日期的最后一天</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">LocalDate.of(<span class="number">2021</span>, <span class="number">1</span>, <span class="number">31</span>).plusMonths(<span class="number">1</span>); <span class="comment">//2021-02-28</span></span><br></pre></td></tr></table></figure>

<p>获取相关属性：getXxx()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回localDateTime对象的日期是这个月的第几天</span></span><br><span class="line">localDateTime.getDayOfMonth(); </span><br><span class="line"><span class="comment">//返回localDateTime对象的星期枚举对象</span></span><br><span class="line">localDateTime.getDayOfWeek();</span><br><span class="line"><span class="comment">//返回localDateTime对象的星期枚举对象对应的值：星期一是1 星期日是7</span></span><br><span class="line">localDateTime.getDayOfWeek().getValue();</span><br><span class="line"><span class="comment">//返回localDateTime对象的月份值</span></span><br><span class="line">localDateTime.getMonthValue();</span><br><span class="line"><span class="comment">//返回localDateTime对象的小时值</span></span><br><span class="line">localDateTime.getHour();</span><br></pre></td></tr></table></figure>



<h3 id="三、格式化与解析"><a href="#三、格式化与解析" class="headerlink" title="三、格式化与解析"></a>三、格式化与解析</h3><h4 id="1、SimpleDateFormat"><a href="#1、SimpleDateFormat" class="headerlink" title="1、SimpleDateFormat"></a>1、SimpleDateFormat</h4><p>SimpleDateFormat是对Date类的格式化与解析，JDK1.8之后出现了DateTimeFormatter类，并且Date类大部分方法被Deprecated，因而SimpleDateFormat的使用也相应的减少了。</p>
<p>实例化可使用默认构造器，也可以调用带有格式的构造器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1）使用默认构造器</span></span><br><span class="line">SimpleDateFormat dateFormat = <span class="keyword">new</span> SimpleDateFormat();</span><br><span class="line"><span class="comment">//2）调用带日期格式参数的构造器创建对象</span></span><br><span class="line">SimpleDateFormat dateFormat1 = <span class="keyword">new</span> SimpleDateFormat(<span class="string">&quot;yyyy-MM-dd HH:mm:ss&quot;</span>);</span><br><span class="line">SimpleDateFormat dateFormat2 = <span class="keyword">new</span> SimpleDateFormat(<span class="string">&quot;yyyy-MM-dd&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>格式化操作：format方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Date date = <span class="keyword">new</span> Date();</span><br><span class="line"><span class="comment">// 格式化</span></span><br><span class="line">String s = dateFormat.format(date); <span class="comment">//2021/2/8 下午4:02</span></span><br><span class="line">String s1 = dateFormat1.format(date); <span class="comment">//2021-02-08 16:02:26</span></span><br><span class="line">String s2 = dateFormat2.format(date); <span class="comment">//2021-02-08</span></span><br></pre></td></tr></table></figure>

<p>解析操作：parse方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String str = <span class="string">&quot;2021/2/3 下午10:00&quot;</span>; <span class="comment">//该字符串必须跟格式化出来的一致</span></span><br><span class="line">Date date1 = dateFormat.parse(str);<span class="comment">//Wed Feb 03 22:00:00 CST 2021</span></span><br><span class="line">String str2 = <span class="string">&quot;2020-12-31 23:50:00&quot;</span>;</span><br><span class="line">Date date1 = dateFormat2.parse(str2);<span class="comment">//Thu Dec 31 23:50:00 CST 2020</span></span><br></pre></td></tr></table></figure>

<h4 id="2、DateTimeFormatter"><a href="#2、DateTimeFormatter" class="headerlink" title="2、DateTimeFormatter"></a>2、DateTimeFormatter</h4><p>DateTimeFormatter类似于SimpleDateFormat，一般有三种格式：ISO标准格式、formatStyle格式、自定义格式，其中自定义格式使用较多</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1）ISO标准格式</span></span><br><span class="line">DateTimeFormatter formatter1 = DateTimeFormatter.ISO_DATE_TIME;</span><br><span class="line"></span><br><span class="line"><span class="comment">//2）FormatStyle格式：LONG MEDIUM SHORT FULL</span></span><br><span class="line"><span class="comment">//注：jdk11下需要调用withZone(ZoneId.systemDefault())方法用于设置为系统默认时区。</span></span><br><span class="line">DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withZone(ZoneId.systemDefault());</span><br><span class="line"></span><br><span class="line"><span class="comment">//自定义格式</span></span><br><span class="line">DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern(<span class="string">&quot;yyyy-MM-dd HH:mm:ss&quot;</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>格式化：format方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">String s1 = formatter1.format(LocalDateTime.now());</span><br><span class="line"><span class="comment">//input：2021-02-08T16:09:53.324125</span></span><br><span class="line"></span><br><span class="line">String s2 = formatter2.format(LocalDateTime.now());</span><br><span class="line"><span class="comment">//input：2021年2月8日 CST 下午4:09:53</span></span><br><span class="line"></span><br><span class="line">String s3 = formatter3.format(LocalDateTime.now());</span><br><span class="line"><span class="comment">//input：2021-02-08 16:09:53</span></span><br></pre></td></tr></table></figure>

<p>解析：parse方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">TemporalAccessor parse = formatter3.parse(<span class="string">&quot;2021-02-04 20:50:10&quot;</span>);</span><br><span class="line"><span class="comment">//input：&#123;&#125;,ISO resolved to 2021-02-04T20:50:10</span></span><br></pre></td></tr></table></figure>

<h3 id="四、java-time到其他时间类的转换"><a href="#四、java-time到其他时间类的转换" class="headerlink" title="四、java.time到其他时间类的转换"></a>四、java.time到其他时间类的转换</h3><p>Instant—&gt;java.util.Date    Date.from(instant)</p>
<p>Instant&lt;—java.util.Date    date.toInstant()</p>
<p>LocalDate—&gt;java.sql.Date    Date.valueOf(localDate)</p>
<p>LocalDate&lt;—java.sql.Date    date.toLocalDate()</p>
<p>LocalTime—&gt;java.sql.Time    Time.valueOf(localTime)</p>
<p>LocalTime&lt;—java.sql.Time    time.toLocalTime()</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">h0ss</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://blog.gpnusz.cn/2021/02/08/JAVA%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86/">https://blog.gpnusz.cn/2021/02/08/JAVA%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://blog.gpnusz.cn" target="_blank">后端学习记录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/02/19/Linux%E5%AF%86%E7%A0%81%E9%87%8D%E7%BD%AE%E7%9B%B8%E5%85%B3%E6%93%8D%E4%BD%9C/"><img class="prev-cover" src="https://www.hualigs.cn/image/602e9827d02a7.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Linux密码重置相关操作</div></div></a></div><div class="next-post pull-right"><a href="/2021/02/06/Linux%E6%9C%8D%E5%8A%A1%E7%AE%A1%E7%90%86%E5%91%BD%E4%BB%A4/"><img class="next-cover" src="https://www.hualigs.cn/image/601e7559be700.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Linux服务管理命令</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/11/16/给开源项目提了个PR/" title="给开源项目提了个PR"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-16</div><div class="title">给开源项目提了个PR</div></div></a></div><div><a href="/2022/08/21/【Debug】bitField-引发的栈溢出排错记/" title="【Debug】bitField 引发的栈溢出排错记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-21</div><div class="title">【Debug】bitField 引发的栈溢出排错记</div></div></a></div><div><a href="/2022/07/16/【RPC】详解SPI机制/" title="【RPC】详解SPI机制"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-16</div><div class="title">【RPC】详解SPI机制</div></div></a></div><div><a href="/2022/07/10/【RPC】基本网络通信模型/" title="【RPC】基本网络通信模型"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">【RPC】基本网络通信模型</div></div></a></div><div><a href="/2022/07/02/【JVM】类加载全过程简记/" title="【JVM】类加载全过程简记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-02</div><div class="title">【JVM】类加载全过程简记</div></div></a></div><div><a href="/2022/06/28/【RPC】RPC实战与核心的学习笔记/" title="【RPC】RPC实战与核心的学习笔记"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-28</div><div class="title">【RPC】RPC实战与核心的学习笔记</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">h0ss</div><div class="author-info__description">一个苦逼后端仔的学习记录</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/h0ss"><i class="fab fa-github"></i><span>Gitee仓库</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">Java后端技术栈语雀文档：https://www.yuque.com/oliver-wdtb1/java</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/" title="给开源项目提了个PR">给开源项目提了个PR</a><time datetime="2022-11-15T17:28:40.000Z" title="发表于 2022-11-16 01:28:40">2022-11-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/09/03/%E3%80%90MySQL%E3%80%91InnoDB%E7%9A%84%E8%A1%8C%E6%A0%BC%E5%BC%8F/" title="【MySQL】InnoDB的行格式">【MySQL】InnoDB的行格式</a><time datetime="2022-09-02T18:17:38.000Z" title="发表于 2022-09-03 02:17:38">2022-09-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/08/21/%E3%80%90Debug%E3%80%91bitField-%E5%BC%95%E5%8F%91%E7%9A%84%E6%A0%88%E6%BA%A2%E5%87%BA%E6%8E%92%E9%94%99%E8%AE%B0/" title="【Debug】bitField 引发的栈溢出排错记">【Debug】bitField 引发的栈溢出排错记</a><time datetime="2022-08-20T18:10:40.000Z" title="发表于 2022-08-21 02:10:40">2022-08-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/16/%E3%80%90RPC%E3%80%91%E8%AF%A6%E8%A7%A3SPI%E6%9C%BA%E5%88%B6/" title="【RPC】详解SPI机制">【RPC】详解SPI机制</a><time datetime="2022-07-15T18:51:57.000Z" title="发表于 2022-07-16 02:51:57">2022-07-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/14/%E3%80%90Redis%E3%80%91%E9%87%8D%E8%A6%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%9F%BA%E7%A1%80/" title="【Redis】重要数据结构基础">【Redis】重要数据结构基础</a><time datetime="2022-07-13T17:22:08.000Z" title="发表于 2022-07-14 01:22:08">2022-07-14</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="爱国,敬业,诚信,友善,自由,平等,公正,法治,富强,民主,文明,和谐" data-fontsize="16px" data-random="false" async="async"></script></div></body></html>